#ifndef ___________WARD____LISTBOX_CPP
#define ___________WARD____LISTBOX_CPP

#include "driver.h"
#include "listbox.h"


listBox::listBox(int x, int y, int maxVisible, int w, string source, bool updown)
{
 unsigned int i; 
 
 xpos = x; 
 ypos = y; 
 maxVis = maxVisible; 
 width = w; 
 curr = 0;
 
 top = 0; 
 vector<string> items = loadFrom(source); 
 for(i = 0; i < items.size(); i++) 
	 entries.push_back(new textBox(xpos,(ypos+(16*i)),w ,items[i])); 
 entries[curr]->select();
 scroll = updown;
}

void listBox::drawEnabled(int xpos, int ypos)
{
int i = 0;
glColor4f(0.0,0.0,0.0,1.0);
glRectf(xpos-20,ypos,xpos+width,ypos+(maxVis*18)+3);
for(i = top; i < min((int)entries.size(),(int)(top+maxVis)); i++)
	entries[i]->drawAt(xpos,ypos+(18*(i-top)));
for(; i < (top+maxVis); i++)
{
textBox temp(0,0,width,"");
temp.drawAt(xpos,ypos+(18*(i-top)));
}

if(scroll)
{
glColor4f(cPri[0],cPri[1],cPri[2],1.0);
glRectf(xpos-20,ypos,xpos-2,ypos+(maxVis*18)-18);
glColor4f(cSec[0],cSec[1],cSec[2],1.0);
glRectf(xpos-20,ypos,xpos-2,ypos+18);
glRectf(xpos-20,ypos+(maxVis*18)-18,xpos-2,ypos+(maxVis*18));
glColor4f(cPri[0],cPri[1],cPri[2],1.0);
writeText(xpos-15,ypos+18,0.1,0.1,0,"^");
writeText(xpos-15,ypos+(maxVis*18)-5,0.1,0.1,0,"v");
glColor4f(cTer[0],cTer[1],cTer[2],1.0);
glRectf(xpos-20,ypos+18+((maxVis-2)*18)*((float)top/entries.size()),xpos-2,ypos+18+((maxVis-2)*18)*((float)top/entries.size())+2);

}
}



vector<string> listBox::loadFrom(string src)
{
vector<string> ret;
ifstream ifs(src.c_str());
string s;
while(!ifs.eof())
{
getline(ifs,s);
if(!ifs.eof())
	ret.push_back(s);

}

ifs.close();
return ret;

}

bool listBox::clicked(int x, int y)
{ 
if(scroll)
{
	if((x>=(xpos-18))&&(x<=(xpos))&&((y>=(ypos))&&(y<=ypos+18))) 
	{
		clicktype = LISTBOX_UP; 
		return true;
	} 


	if( ((x>=(xpos-18)) && (x<=(xpos))) && ((y >= (ypos+(maxVis*18)-18) ) && ( y <= (ypos+(maxVis*18)) ))) 
	{
		clicktype = LISTBOX_DOWN; 
		return true;
	} 
}
	if((x>=xpos)&&(x<=(xpos+width))&&(y >= ypos)&&(y <= (ypos+(maxVis*18) )))
	{
		clicktype = LISTBOX_SELECT;
		clickY = y;
		return true;
	}
	return false;
}

void listBox::onClick()
{ 

	switch(clicktype)
	{
	case LISTBOX_UP: {	top = max(top-1,0); break;}
	
	case LISTBOX_DOWN:	{	if((top+maxVis-1) != (entries.size()-1)) top = min((int)top+1,(int)entries.size()-1);	break; }

	case LISTBOX_SELECT: 	{	unsigned int selected = ((clickY-ypos)/18)+top;	if(selected < entries.size()){if(curr != -1) entries[curr]->select(); curr = selected;	entries[curr]->select();}}
	}


}



#endif